<?php

namespace app\api\controller;

use app\admin\model\cms\Video as VideoModel;
use app\common\model\Comment;
use app\common\model\UserFavorite;
use app\common\model\UserLike;
use think\Db;
use think\Env;

/**
 * 视频
 */
class Video extends Base
{
    protected $model;

    protected $noNeedLogin = ['list', 'detail', 'calendarTag'];

    public function _initialize()
    {
        parent::_initialize();
        //检测ID是否加密
//        $this->hashids();
    }

    /**
     * 投研视频列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function list()
    {
        $video = new VideoModel();
        $where = [];
        $param = $this->request->param();

        isset($param['title']) && $param['title'] && $where[] = ['title', 'like', '%' . $param['title'] . '%'];
        if (isset($param['title']) && $param['title']) {
            $video->where('title', 'like', '%' . $param['title'] . '%');
        }
        if (isset($param['create_time']) && $param['create_time']) {
            $start = $param['create_time'];
            $end = date('Y-m-d', strtotime(sprintf('%s +1 day', $param['create_time'])));
            $video->whereTime('create_time', 'between', [$start, $end]);
        }
        $list = $video->order('id DESC')->paginate($param['per_page'] ?? 10);
        $http = Env::get('local.img_domain');
        foreach ($list as $row) {
            if (mb_substr($row['image'], 0, 9, 'utf-8') == "/uploads/") {
                $row['image'] = $http . $row['image'];
            }
            if (mb_substr($row['video_path'], 0, 9, 'utf-8') == "/uploads/") {
                $row['video_path'] = $http . $row['video_path'];
            }
        }
        $this->success('', ['list' => $list]);
    }

    /**
     * 视频详情
     * @param $id
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail($id)
    {
        $vObj = new VideoModel();
        $info = $vObj->with('user')->where('id', $id)->find();
        if (!$info) {
            $this->error("视频不存在！");
        }
        $uid = $this->auth->id ?? 0;

        $info['is_favorite'] = 0;
        $fav = Db::name('user_favorite')->where(['object_id' => $id, 'table_name' => 'video', 'user_id' => $uid])->find();
        if ($fav) {
            $info['is_favorite'] = 1;
        }
        $info['is_like'] = 0;
        $like = Db::name('user_like')->where(['object_id' => $id, 'table_name' => 'video', 'user_id' => $uid])->find();
        if ($like) {
            $info['is_like'] = 1;
        }

        // 浏览量+1
        $vObj->where('id', $id)->setInc('count_view');
        // 刷新评论数
        $total = Db::name('comment')->where(['aid' => $id, 'type' => 'video'])->count();
        $vObj->where('id', $id)->update(['count_comment' => $total]);

        // 评论列表
        $commentList = Comment::getCommentList(['aid' => $id, 'type' => 'video']);
        $commentList = $commentList->getCollection();
        foreach ($commentList as &$item) {
            if ($item->user) {
                $item->user->avatar = cdnurl($item->user->avatar, true);
                $item->user->visible(explode(',', 'id,nickname,avatar,bio'));
            }
            $item->hidden(['ip', 'useragent', 'status', 'delete_time', 'aid', 'subscribe', 'post_status', 'type', 'updatetime', 'deletetime']);
        }
        $this->success('', ['info' => $info->toArray(), 'commentList' => $commentList]);
    }

    /**
     * 收藏视频
     * @param $id
     * @return void
     */
    public function doFavorite($id)
    {
        $videoInfo = (new VideoModel())->find($id);
        if (!$videoInfo) {
            $this->error("视频不存在！");
        }
        $uid = $this->auth->id ?? 0;

        $where = ['object_id' => $id, 'table_name' => 'video', 'user_id' => $uid];
        $info = Db::name('user_favorite')->where($where)->find();
        if (!$info) {
            Db::name('user_favorite')->insert([
                'user_id' => $uid,
                'table_name' => 'video',
                'object_id' => $id,
                'create_time' => time(),
            ]);
            (new VideoModel())->where('id', $id)->update(['count_like' => UserFavorite::favTotal($id, 'video')]);
        }
        $this->success("收藏成功！");
    }

    /**
     * 取消收藏视频
     * @param int $id 视频id
     * @return void
     */
    public function cancelFavorite($id)
    {
        $uid = $this->auth->id ?? 0;
        (new UserFavorite())->where(['object_id' => $id, 'table_name' => 'video', 'user_id' => $uid])->delete();
        (new VideoModel())->where('id', $id)->update(['count_like' => UserFavorite::favTotal($id, 'video')]);
        $this->success("已取消收藏！");
    }

    /**
     * 点赞视频
     * @param $id
     * @return void
     */
    public function doLike($id)
    {
        $videoInfo = (new VideoModel())->find($id);
        if (!$videoInfo) {
            $this->error("视频不存在！");
        }
        $uid = $this->auth->id ?? 0;

        $likeObj = Db::name('user_like');
        $where = ['object_id' => $id, 'table_name' => 'video', 'user_id' => $uid];
        $info = $likeObj->where($where)->find();
        if (!$info) {
            $likeObj->insert([
                'user_id' => $uid,
                'table_name' => 'video',
                'object_id' => $id,
                'create_time' => time(),
            ]);
            (new VideoModel())->where('id', $id)->update(['count_like' => UserLike::likeTotal($id, 'video')]);
        }
        $this->success("点赞成功！");
    }

    /**
     * 取消点赞视频
     * @param int $id 视频id
     * @return void
     */
    public function cancelLike($id)
    {
        $uid = $this->auth->id ?? 0;
        Db::name('user_like')->where(['object_id' => $id, 'table_name' => 'video', 'user_id' => $uid])->delete();
        (new VideoModel())->where('id', $id)->update(['count_like' => UserLike::likeTotal($id, 'video')]);
        $this->success("已取消点赞！");
    }

    /**
     * 发表视频评论
     * @param $id
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addComment($id)
    {
        $config = config();
        $useragent = substr(request()->server('HTTP_USER_AGENT', ''), 0, 255);
        $ip = request()->ip(0, false);

        $params = $this->request->post();
        $uid = $this->auth->id ?? 2;

        $vInfo = VideoModel::get($id);
        if (!$vInfo) {
            $this->error("视频已删除！！");
        }
        if ($vInfo['iscomment'] == 0) {
            $this->error("该视频评论功能未开启！！");
        }

        if (!isset($params['content']) || !$params['content']) {
            $this->error("评论内容不能空！");
        }
        if (strlen($params['content']) < 2) {
            $this->error("请输入2个字符以上！");
        }

        //查找最后评论
        $lastComment = Comment::where(['type' => 'video', 'aid' => $id, 'ip' => $ip])->order('id', 'desc')->find();
        if ($lastComment && time() - intval($lastComment['createtime']) < 30) {
            $this->error("发表评论过快！");
        }
        if ($lastComment && $lastComment['content'] == $params['content']) {
            $this->error("该评论内容已经发布过了！");
        }

        //审核状态
        $status = 'normal';
        $config['iscommentaudit'] = 0;
        if ($config['iscommentaudit'] == 1) {
            $status = 'hidden';
        } elseif ($config['iscommentaudit'] == 0) {
            $status = 'normal';
        } elseif ($config['iscommentaudit'] == -1) {
            if (!\app\api\library\Service::isContentLegal($params['content'])) {
                $status = 'hidden';
            }
        }

        $data = [
            'aid' => $id,
            'user_id' => $uid,
            'pid' => $params['pid'] ?? 0,
            'type' => 'video',
            'content' => nl2br($params['content']),
            'ip' => $ip,
            'useragent' => $useragent,
            'status' => $status,
        ];
        $model = new Comment();
        $model->allowField(true)->save($data);

        //发送通知
        if ($status === 'hidden') {
            Comment::notice(config('pro.sitename') . '收到一条待审核评论');
        }
        $this->success("评论成功，审核后将展示！");
    }

    /**
     * 日历标记（指定月份，有视频的日期标记出来）
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function calendarTag()
    {
        $param = $this->request->param();
        if (!isset($param['year_month']) || strlen($param['year_month']) != 7) {
            $this->error("日期参数错误！！");
        }
        $start = strtotime($param['year_month']);
        $end = strtotime(sprintf('%s +1month', $param['year_month']));
        $list = (new VideoModel())->field('id,create_time as time')->whereBetween('create_time', [$start, $end])->select();
        $temp = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'];
        $month = [];
        foreach ($temp as $item) {
            $month [sprintf('%s-%s', $param['year_month'], $item)] = 0;
        }
        foreach ($list as $row) {
            // 天数不要前面的0
            $day = date('Y-m-d', $row->time);
            isset($month[$day]) && $month[$day] += 1;
        }
        $this->success('', ['days' => $month, 'month' => $param['year_month']]);
    }
}
